import SparkMD5 from 'spark-md5'
/**
 * 分片获取md5值
 * @param {*} file 文件对象
 * @param {*} chunkSize 分片大小
 * @param {*} progressCallback 进度修改回调
 * @returns 
 */
let fileMd5 = (file, chunkSize, progressCallback = console.log) => {
    return new Promise((resolve, reject) => {
      const blobSlice =
        File.prototype.slice ||
        File.prototype.mozSlice ||
        File.prototype.webkitSlice
      let chunks = Math.ceil(file.size / chunkSize)
      let currentChunk = 0
      let spark = new SparkMD5.ArrayBuffer()
      let fileReader = new FileReader()
      fileReader.onerror = reject
      fileReader.onload = (e) => {
        progressCallback(currentChunk / chunks)
        spark.append(e.target.result)
        currentChunk++
        if (currentChunk < chunks) {
          loadNext()
        } else {
          resolve(spark.end())
        }
      }
      function loadNext() {
        let start = currentChunk * chunkSize
        let end = start + chunkSize >= file.size ? file.size : start + chunkSize
        fileReader.readAsArrayBuffer(blobSlice.call(file, start, end))
      }
      loadNext()
    })
  }
  

export default fileMd5